package com.vn.bklegends.xonefm;

import java.util.ArrayList;

import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

    private ListView listData;
    private ArrayList<News> listObject;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.activity_main);

	listData = (ListView) findViewById(R.id.listView1);

	listData.setOnItemClickListener(new OnItemClickListener() {

	    @Override
	    public void onItemClick(AdapterView<?> arg0, View arg1,
		    int position, long arg3) {
		PlayActivity.news = listObject.get(position);
		startActivity(new Intent(MainActivity.this, PlayActivity.class));
	    }
	});
	listObject = new ArrayList<News>();
	new LoadData().execute();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	// Inflate the menu; this adds items to the action bar if it is present.
	getMenuInflater().inflate(R.menu.main, menu);
	return true;
    }

    class LoadData extends AsyncTask<Void, Void, Void> {

	private ArrayList<String> getData = new ArrayList<String>();
	private ProgressDialog dialog;

	public LoadData(){
	    dialog = new ProgressDialog(MainActivity.this);
	    dialog.setMessage("Đang tải dữ liệu...");
	    dialog.show();
	}
	@Override
	protected Void doInBackground(Void... params) {
	    // TODO Auto-generated method stub
	    getData = OnlineContentReader
		    .getStringArrayFromURL(MainActivity.this.getResources()
			    .getString(R.string.host));
	    return null;
	}

	@Override
	protected void onPostExecute(Void result) {
	    dialog.dismiss();
	    if (getData.size() != 0) {
		for (int i = 0; i < getData.size(); i++) {
		    String[] split = getData.get(i).split(",");
		    listObject.add(new News(split[0], split[1], split[2],split[3]));
		    getData.set(i, split[2]);
		}
		listData.setAdapter(new ArrayAdapter<String>(MainActivity.this,
			android.R.layout.simple_list_item_1, getData));
	    }
	    super.onPostExecute(result);
	}

    }
}
